import {
  Box,
  Button,
  Card,
  CardBody,
  Divider,
  Flex,
  Heading,
  Stack,
  Image,
  useMediaQuery,
} from '@chakra-ui/react';
import React, { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../../redux/hooks';
import { setActiveTheme } from '../../redux/themes/slices';
import getAllThemesThunk from '../../redux/themes/thunks';
import useSocket from '../hooks/useSocket';

export default function Theme(): React.JSX.Element {
  const [isLargerThanPhone] = useMediaQuery('(min-width: 800px)');

  const themes = useAppSelector((state) => state.themes.themes);
  const dispatch = useAppDispatch();
  useSocket();
  const { createRoomHandler } = useSocket();

  useEffect(() => {
    void dispatch(getAllThemesThunk());
  }, [dispatch]);

  const handlePlay = (themeId: number): void => {
    dispatch(setActiveTheme(themeId));
    createRoomHandler(themeId);
  };

  return (
    <Box
      bgImage="url('/img/11.png')"
      bgSize="cover"
      bgPosition="center"
      minHeight="100vh"
      display="flex"
      flexDirection="column"
      justifyContent="center"
      alignItems="center"
      paddingY="8"
    >
      <Heading as="h2" size={isLargerThanPhone ? 'lg' : 'md'} mb={4} color="white" fontSize="40px">
        ВЫБЕРИ ТЕМУ
      </Heading>
      <Flex justifyContent="space-around" gap={4} flexWrap="wrap" fontSize="57">
        {themes.map((theme) => (
          <Card
            key={theme.id}
            minH="300px"
            minW="300px"
            m={8}
            width="20%"
            transition="height 0.5s, transform 0.5s"
            _hover={{
              transform: 'scale(1.09)',
            }}
          >
            <CardBody
            
              display="flex"
              flexDirection="column"
              justifyContent="center"
              alignItems="center"
              transition="top 0.5s, height 0.5s"
            >
              <Image
                src={import.meta.env.VITE_URL === '/' ? theme.image : `${import.meta.env.VITE_URL}/${theme.image}`}
                alt="Green double couch with wooden legs"
                maxWidth="80%"
              />
              <Stack mt="6" spacing="3" textAlign="center">
                <Heading size="md" fontSize="40px"
>{theme.title}</Heading>
              </Stack>
            </CardBody>
            <Divider />

            <Button
              variant="solid"
              height="12"
              colorScheme="yellow"
              onClick={() => handlePlay(theme.id)}
              
            >
              ИГРАТЬ
            </Button>
          </Card>
        ))}
      </Flex>
    </Box>
  );
}
